package com.xiangyueEducation.uploaderCloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangyueEducation.uploaderCloud.mapper.ArticleMapper;
import com.xiangyueEducation.uploaderCloud.pojo.dto.PageQuery;
import com.xiangyueEducation.uploaderCloud.pojo.entity.Article;
import com.xiangyueEducation.uploaderCloud.pojo.vo.ArticleMainVo;
import com.xiangyueEducation.uploaderCloud.pojo.vo.PageVo;
import com.xiangyueEducation.uploaderCloud.service.ArticleService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public PageVo pageQuery(PageQuery pageQuery, String keyword) {
        Integer pageSize = pageQuery.getPageSize();
        Integer pageNo = pageQuery.getPageNo();
        //添加分页基本参数
        Page<Article> articlePage = new Page<>(pageNo, pageSize);
        //设置排序参数，按照时间顺序，升序
        OrderItem orderItem1 = new OrderItem().setAsc(true).setColumn("create_time");
        articlePage.addOrder(orderItem1);
        List<String> list = List.of(new String[]{"id","topic","create_time"});
        //去数据库查
        Page<Article> page = null;
        if (keyword==null||keyword.isBlank()){
             page = page(articlePage,new QueryWrapper<Article>().select(list));
        }
        else page = page(articlePage,new QueryWrapper<Article>().select(list).like("topic", keyword));
        List<ArticleMainVo> records = page.getRecords().stream().map((article -> new ArticleMainVo(article.getId(),article.getTopic(), article.getCreateTime(),article.getIntroduction()))).collect(Collectors.toList());
        long total = page.getTotal();
        return new PageVo(total,records);
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.updateAll(article);
    }
}
